#include "TCPServer.h"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <string>
#include "../Stringops/StringOps.h"
using namespace std;

int buildServer(int argc, char*argv[]);

bool ipcheck(std::string _host) {
        std::vector<std::string> parts = split(_host, '.');
        for(unsigned int i = 0; i < parts.size(); i++)
                if(!is_numeric(parts[i]))
                        return false;
        return true;
}

int main(int argc, char*argv[]){
	int mainRtn = 0;
	mainRtn = buildServer(argc, argv);
	if(mainRtn < 0) {
		exit(EXIT_FAILURE);
	}
	return mainRtn;	
}

int buildServer(int argc, char*argv[]){
	string _serv_port;
	string _serv_ip;
	string _raw_port;
	char buffer[BUFFER_SIZE];
	if(argc!=4){
		printf("correct command:<server> <server ip> <server port> <raw port>\n");
		return 1;
	}else{
		_raw_port = argv[3];
		_serv_port = argv[2];
		_serv_ip = argv[1];
		if(ipcheck(_serv_ip) && is_numeric(_serv_port) && is_numeric(_raw_port)){
			TCPServer myServ(_serv_ip, atoi(_serv_port.c_str()), atoi(_raw_port.c_str()));
			if(myServ.incoming_sock == null) {
				// Couldn't bind to port
				return -1;
			}
			TCPConnection servConn = myServ.receive_incoming_connection();
			if(servConn.sock == null) {
				// Couldn't get the connection
				return -1;
			}
			myServ.handle_server_connection(myServ,servConn,buffer);
			myServ.stop_server();
		}else{
			printf("server ip, port number and max client should be correct!\n");
			return 1;
		}
			
	}	
	return 0;
}
